package com.it.schoolbookshop_back.service.impl;

import com.it.schoolbookshop_back.entities.po.Category;
import com.it.schoolbookshop_back.mapper.CategoryMapper;
import com.it.schoolbookshop_back.service.CategoryService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.findAll();
    }

    @Override
    public List<Category> getAllCategoriesWithBookCount() {
        // 方法1：直接使用SQL连接查询（推荐）
        return categoryMapper.findAllWithBookCount();
        
        /* 方法2：先查询所有分类，再查询书籍数量并设置（仅作为备选方案）
        List<Category> categories = categoryMapper.findAll();
        Map<Integer, Integer> bookCountMap = new HashMap<>();
        
        // 获取所有分类的书籍数量
        List<Map<String, Object>> bookCounts = categoryMapper.getAllCategoriesBookCount();
        for (Map<String, Object> count : bookCounts) {
            bookCountMap.put((Integer) count.get("key"), ((Number) count.get("value")).intValue());
        }
        
        // 设置每个分类的书籍数量
        for (Category category : categories) {
            Integer count = bookCountMap.get(category.getId());
            category.setBookCount(count != null ? count : 0);
        }
        
        return categories;
        */
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryMapper.findById(id);
    }

    @Override
    public Category getCategoryByIdWithBookCount(Integer id) {
        // 方法1：直接使用SQL连接查询（推荐）
        return categoryMapper.findByIdWithBookCount(id);
        
        /* 方法2：先查询分类，再查询书籍数量（仅作为备选方案）
        Category category = categoryMapper.findById(id);
        if (category == null) {
            return null;
        }
        
        // 查询该分类下的书籍数量
        int bookCount = categoryMapper.countBooksByCategory(id);
        category.setBookCount(bookCount);
        
        return category;
        */
    }

    @Override
    public Integer createCategory(Category category) {
        // 检查分类名称是否已存在
        if (isCategoryNameExists(category.getName())) {
            return null;
        }
        
        // 插入分类
        int result = categoryMapper.insert(category);
        return result > 0 ? category.getId() : null;
    }

    @Override
    public boolean updateCategory(Category category) {
        // 检查分类是否存在
        if (category.getId() == null || categoryMapper.findById(category.getId()) == null) {
            return false;
        }
        
        // 检查分类名称是否已被其他分类使用
        if (isCategoryNameExists(category.getName(), category.getId())) {
            return false;
        }
        
        // 执行更新
        int result = categoryMapper.update(category);
        return result > 0;
    }

    @Override
    public boolean deleteCategory(Integer id) {
        // 检查分类是否存在
        if (id == null || categoryMapper.findById(id) == null) {
            return false;
        }
        
        // 执行删除
        int result = categoryMapper.deleteById(id);
        return result > 0;
    }

    @Override
    public boolean isCategoryNameExists(String name) {
        Category category = categoryMapper.findByName(name);
        return category != null;
    }

    @Override
    public boolean isCategoryNameExists(String name, Integer excludeId) {
        Category category = categoryMapper.findByName(name);
        // 如果找不到同名分类，或者找到的分类就是要排除的分类，则表示不存在
        return category != null && !category.getId().equals(excludeId);
    }
} 